/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.utils.middleware;

import java.util.LinkedList;
import java.util.regex.Pattern;

import org.testis.orm.classes.T_test_label;
import org.testis.orm.classes.T_test_label_inclusion;

/**
 * 
 * @author selcuk
 */
public class LabelUtils {

    public static T_test_label getParentLabel(T_test_label label) {
	T_test_label parent = null;
	if (!label.t_test_label_inclusion1.isEmpty()) {
	    // System.out.println(label.getName() +
	    // ": t_test_label_inclusion1 is not empty");
	    T_test_label_inclusion[] inclusions = label.t_test_label_inclusion1
		    .toArray();
	    parent = inclusions[0].getContainer();
	}
	return parent;
    }

    public static String convertLabelsToString(T_test_label[] labels,
	    boolean inheritance) {
	StringBuilder sb = new StringBuilder();
	if (labels == null) {
	    return sb.toString();
	}

	for (int i = 0; i < labels.length; i++) {
	    String labelName = labels[i].getName();
	    if (sb.indexOf(labelName) == -1) {
		sb.append(labelName + " ");
	    }
	    if (inheritance) {
		T_test_label parent = getParentLabel(labels[i]);
		while (parent != null) {
		    labelName = parent.getName();
		    if (sb.indexOf(labelName) == -1) {
			sb.append(labelName + " ");
		    }
		    parent = getParentLabel(parent);
		}
	    }
	}
	return sb.toString();
    }

    public static String convertLabelsToString(
	    LinkedList<T_test_label> labelLinkedList, boolean inheritance) {
	String result = "";
	if (labelLinkedList != null) {
	    T_test_label[] labels = new T_test_label[labelLinkedList.size()];
	    labelLinkedList.toArray(labels);
	    result = convertLabelsToString(labels, inheritance);
	}
	return result;
    }

    public static boolean matchesLabelPattern(String regex,
	    T_test_label[] labels, boolean inheritance) {
	String input = convertLabelsToString(labels, true);
	return matchesLabelPattern(regex, input);
    }

    public static boolean matchesLabelPattern(String regex,
	    LinkedList<T_test_label> labels, boolean inheritance) {
	String input = convertLabelsToString(labels, true);
	return matchesLabelPattern(regex, input);
    }

    public static boolean matchesLabelPattern(String regex, String input) {
	Pattern p = Pattern.compile(regex);
	return p.matcher(input).matches();
    }
}
